package com.itheima.health.filter;

import com.itheima.health.common.MessageConst;
import com.itheima.health.pojo.entity.Permission;
import com.itheima.health.pojo.entity.Role;
import com.itheima.health.pojo.entity.User;
import com.itheima.health.pojo.result.Result;
import com.itheima.health.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 权限过滤器
 */
@WebFilter(urlPatterns = "/*")
@Slf4j
public class AuthFilter implements Filter {
    // 无需登录可直接访问的URI
    private String[] anonymousAccessUriList = new String[]{
            "/user/login",
            "/user/logout",
            "/mobile/**"
    };

    // 定义URI所需权限
    private Map<String, String> uriPermissionMap = new HashMap<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        initUriPermissionMap();
    }

    /**
     * 初始化URI与所需权限间的映射关系
     */
    private void initUriPermissionMap() {
        // 设置需要检查项相关权限的URI
        uriPermissionMap.put("/checkitem/findPage", "CHECKITEM_QUERY");
        uriPermissionMap.put("/checkitem/findById", "CHECKITEM_QUERY");
        uriPermissionMap.put("/checkitem/add", "CHECKITEM_ADD");
        uriPermissionMap.put("/checkitem/delete", "CHECKITEM_DELETE");
        uriPermissionMap.put("/checkitem/edit", "CHECKITEM_EDIT");

        // 设置需要检查组相关权限的URI
        uriPermissionMap.put("/checkgroup/findPage", "CHECKGROUP_QUERY");
        uriPermissionMap.put("/checkgroup/findById", "CHECKGROUP_QUERY");
        uriPermissionMap.put("/checkgroup/findCheckItemIdsByCheckGroupId", "CHECKGROUP_QUERY");
        uriPermissionMap.put("/checkitem/findAll", "CHECKGROUP_QUERY");
        uriPermissionMap.put("/checkgroup/add", "CHECKGROUP_ADD");
        uriPermissionMap.put("/checkgroup/deleteCheckGroupitemById", "CHECKGROUP_DELETE");
        uriPermissionMap.put("/checkgroup/edit", "CHECKGROUP_EDIT");

        // 设置需要套餐相关权限的URI
        uriPermissionMap.put("/setmeal/findPage", "SETMEAL_QUERY");
        uriPermissionMap.put("/setmeal/findById", "SETMEAL_QUERY");
        uriPermissionMap.put("/checkgroup/findAll", "SETMEAL_QUERY");
        uriPermissionMap.put("/checkgroup/findCheckGroupIdsBySetmealId", "SETMEAL_QUERY");
        uriPermissionMap.put("/setmeal/add", "SETMEAL_ADD");
        uriPermissionMap.put("/setmeal/upload", "SETMEAL_ADD");
        uriPermissionMap.put("/setmeal/deleteSetmealById", "SETMEAL_DELETE");
        uriPermissionMap.put("/setmeal/edit", "SETMEAL_EDIT");

        // 设置需要预约设置相关权限的URI
        uriPermissionMap.put("/ordersetting/**","ORDERSETTING");

        // 设置需要统计分析相关权限的URI
        uriPermissionMap.put("/report/**","REPORT_VIEW");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        String uri = request.getRequestURI();

        if (isAnonymousAccess(uri)) {
            log.info("[权限检查过滤器]uri:{}允许匿名访问", uri);
            filterChain.doFilter(request, response);
            return;
        }

        if (request.getSession().getAttribute("user") != null) {
            User user = (User) request.getSession().getAttribute("user");
            // 判断用户对请求URI是否具有访问权限
            boolean allowAccess = checkAuthURI(uri, user);
            if (allowAccess) {
                filterChain.doFilter(request, response);
            } else {
                HttpUtil.write(response, Result.error(MessageConst.REJECT_ACCESS));
            }
        } else {
            log.warn("[权限检查过滤器]用户未登录，请重新登录");
            HttpUtil.write(response, Result.error(MessageConst.NOT_LOGIN));
        }
    }

    /**
     * 判断URI是否可以匿名访问
     * @param uri
     * @return
     */
    private boolean isAnonymousAccess(String uri) {
        AntPathMatcher pathMatcher = new AntPathMatcher();
        for (String anonymousAccessUri : anonymousAccessUriList) {
            if (pathMatcher.match(anonymousAccessUri, uri)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断用户是否具有访问请求URI的权限
     * @param reqUri 请求URI
     * @param user 用户
     * @return
     */
    private boolean checkAuthURI(String reqUri, User user) {
        // 判断请求URI是否需要权限校验
        AntPathMatcher pathMatcher = new AntPathMatcher();
        Set<String> uriSet = uriPermissionMap.keySet();
        String matchUri = null;
        for (String uri : uriSet) {
            if (pathMatcher.match(uri, reqUri)) {
                matchUri = uri;
            }
        }
        // 如果预定义的uriPermissionMap中没有与请求URI匹配的URI，即表示该请求URI无需权限校验
        if (matchUri == null) {
            log.info("[权限检查过滤器]uri:{}无需权限校验", reqUri);
            return true;
        }
        String authKeyword = uriPermissionMap.get(matchUri);

        // 判断当前用户是否拥有该权限
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                if (permission.getKeyword().equals(authKeyword)) {
                    log.info("[权限检查过滤器]用户具有所需权限，允许访问; 用户id:{}, uri:{}",
                            user.getId(), reqUri);
                    return true;
                }
            }
        }
        log.info("[权限检查过滤器]用户不具有所需权限，拒绝访问; 用户id:{}, uri:{}", user.getId(), reqUri);
        return false;
    }
}
